﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI;
using Microsoft.Practices.Unity;
using Baosight.ZNH.ZMCD.UI.Block;

namespace Baosight.ZNH.ZMCD.UI
{
    public partial class ZMCD13 : EFViewCmes
    {
        private LimitBlock block = new LimitBlock();
        public ZMCD13()
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
        }

        public override void Initialize(EIInfo initData)
        {
            initData.AddBlock(block.GetLimit());
            base.Initialize(initData);
        }

        /// <summary>
        /// 列表中修改、删除前设置属性、参数
        /// 传递到后台代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = _view;
        }

        #region 主表新增 修改 删除
        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            base.OnInsertButtonClickPopup(eiInfo, "目录分类-新增", "insert", null, sender, e);
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();

            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");
            EIRow row = new EIRow();
            if (_list.Count > 0)
            {
                if (_list[0]["fdCreatorId"].Equals(this.EIDataContext.GetAttribute("userId")))
                {
                    row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
                }
                else
                {
                    BaseTools.OpenEFWindowAlert("不能修改，只有该目录的创建人可以修改此目录！", WindowAlertClosed);
                    return;
                }
            }
            eIBlock.SetRow(0, row);
            eiInfo.AddBlock(eIBlock);

            base.OnUpdateButtonClickPopup(eiInfo, "目录分类-修改", "update", null, sender, e);
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InsertWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.grid.Refresh();
                UpdateHomePageData(new EIInfo());
            }

            //按钮生效
            base.TempButtonOpen(true);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            List<EIRow> _eIRows = this.grid.CheckedEIRows;
            if (_eIRows.Count <= 0)
            {
                BaseTools.OpenEFWindowAlert("请选择一条记录删除！", WindowAlertClosed);
                return;
            }
            if (_eIRows.Count == 1)
            {
                if (!_eIRows[0]["fdCreatorId"].Equals(this.EIDataContext.GetAttribute("userId")))
                {
                    BaseTools.OpenEFWindowAlert("不能删除，只有此目录的编制人可以删除此目录！", WindowAlertClosed);
                    return;
                }
                EIInfo info = this.BuildEIData(OperationMode.Query, eServiceName, "canDelete", DataRange.CheckedItems, null);
                this.Submit(info, CanDeleteQueryCompleted);
                return;
            }
            else
            {
                BaseTools.OpenEFWindowAlert("最多只能选择一条记录进行删除！", WindowAlertClosed);
                return;
            }
        }

        /// <summary>
        /// 判断是否能删除的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CanDeleteQueryCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                base.OnDeleteButtonClick(TempButton, null);
                return;
            }
            BaseTools.OpenEFWindowAlert(e.EIInfo.Msg, WindowAlertClosed);
        }

        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            ZMCD12 view = new ZMCD12(_dialogType);//构造一个新的修改页面
            view.EIDataContext = new Platform.Core.UI.EIDataContext();
            view.EIDataContext.Update(_eIInfo);

            if (_dialogType.Equals("insert"))
            {
                view.fdSuperDirId.Value = this.fdSuperDirId.Value;
                view.fdDirType.Value = this.fdDirType.Value;
            }

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = view;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(InsertWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }
        #endregion

        #region 从表新增 修改 删除
        /// <summary>
        /// 权限新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnLimitInsertButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            if (this.grid.SelectedItem != null)
            {
                if (!this.grid.SelectedItem.GetType().GetProperty("fdCreatorId").GetValue(this.grid.SelectedItem, null).Equals(this.EIDataContext.GetAttribute("userId")))
                {
                    BaseTools.OpenEFWindowAlert("不能新增，只有该目录的创建人可以新增该目录的权限！", WindowAlertClosed);
                    return;
                }

                EIInfo info = new EIInfo();
                info.AddBlock(this.EIDataContext.GetBlock("cmes.cd.department1"));
                ZMCD14 insert = new ZMCD14();
                insert.fdDirId.Value = this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null);
                insert.EIDataContext = new Platform.Core.UI.EIDataContext();
                insert.EIDataContext.Update(info);

                CmesWindows _popup = new CmesWindows();//构造一个弹出页面
                _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
                _popup.Header = "添加部门权限";//设置Title
                _popup.Content = insert;//让新增页面在弹出窗口显示
                _popup.Closed += new EventHandler<WindowClosedEventArgs>(LimitInsertWindow_Closed);
                _popup.ShowDialog();//模态显示弹出窗口
            }
            else
            {
                TempButton.IsEnabled = true;
            }
        }

        /// <summary>
        /// 权限修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnLimitUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            if (this.grid.SelectedItem != null)
            {
                if (!this.grid.SelectedItem.GetType().GetProperty("fdCreatorId").GetValue(this.grid.SelectedItem, null).Equals(this.EIDataContext.GetAttribute("userId")))
                {
                    BaseTools.OpenEFWindowAlert("不能修改，只有该目录的创建人可以修改该目录的权限！", WindowAlertClosed);
                    return;
                }

                int count = this.limitGrid.CheckedEIRows.Count;
                if (count <= 0)
                {
                    this.OpenEFWindowAlert("请选择一条记录进行修改！", true);
                    return;
                }
                else if (count > 1)
                {
                    this.OpenEFWindowAlert("最多只能选择一条记录进行修改！", true);
                    return;
                }
                else
                {
                    EIInfo eiInfo = new EIInfo();
                    EIBlock eIBlock = eiInfo.AddBlock("result");
                    eIBlock.SetColumns(this.limitGrid.EIBlock.Columns);
                    eIBlock.SetRow(0, BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("limitresult").GetColumns(), this.limitGrid.CheckedEIRows[0]));
                    eiInfo.AddBlock(block.GetLimit());
                    eiInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cd.department"));

                    ZMCD15 update = new ZMCD15("update");
                    update.fdOrgId.IsEnabled = false;
                    update.EIDataContext = new Platform.Core.UI.EIDataContext();
                    update.EIDataContext.Update(eiInfo);

                    CmesWindows _popup = new CmesWindows();//构造一个弹出页面
                    _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
                    _popup.Header = "修改权限";//设置Title
                    _popup.Content = update;//让新增页面在弹出窗口显示
                    _popup.Closed += new EventHandler<WindowClosedEventArgs>(LimitInsertWindow_Closed);
                    _popup.ShowDialog();//模态显示弹出窗口
                }                
            }
            else
            {
                TempButton.IsEnabled = true;
            }
        }

        /// <summary>
        /// 权限删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnLimitDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            if (this.grid.SelectedItem != null)
            {
                if (!this.grid.SelectedItem.GetType().GetProperty("fdCreatorId").GetValue(this.grid.SelectedItem, null).Equals(this.EIDataContext.GetAttribute("userId")))
                {
                    BaseTools.OpenEFWindowAlert("不能删除，只有该目录的创建人可以删除该目录的权限！", WindowAlertClosed);
                    return;
                }
                
                int count = this.limitGrid.CheckedEIRows.Count;
                if (count <= 0)
                {
                    this.OpenEFWindowAlert("请选择记录进行修改！", true);
                    return;
                }
                else
                {
                    BaseTools.OpenEFWindowConfirm("确定删除所选择的记录？", DeleteLimitConfirmClosed);
                }
            }
            else
            {
                TempButton.IsEnabled = true;
            }
        }

        /// <summary>
        /// 删除确认框，点击确认按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteLimitConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);//取消后，删除按钮生效
                return;
            }

            if (e.DialogResult.Value)
            {
                EIInfo info = new EIInfo();
                info.Set(EIConstants.ServiceNameKey, "ZMCD14");
                info.Set(EIConstants.MethodNameKey, "delete");
                EIBlock block = info.AddBlock("result");
                block.SetColumns(this.limitGrid.EIBlock.GetColumns());
                block.SetRows(this.limitGrid.CheckedEIRows);
                this.Submit(info, DoDeleteLimitCompleted);                
            }
        }

        /// <summary>
        /// 列表页面执行“删除”后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoDeleteLimitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                string _msg;
                if (inInfo.GetMsg() == null || inInfo.GetMsg() == "")
                {
                    _msg = "操作失败！";
                }
                else
                {
                    _msg = inInfo.GetMsg();
                }

                this.OpenEFWindowAlert(_msg, true);//列表中删除，操作失败后按钮生效
                return;
            }
            else
            {
                this.limitGrid.Refresh();
                this.TempButtonOpen(true);//列表中删除，操作成功后按钮生效
            }
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LimitInsertWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.limitGrid.Refresh();
            }

            //按钮生效
            base.TempButtonOpen(true);
        }
        #endregion

        /// <summary>
        /// 重写基类方法：根据数据的改变更新主页面的数据
        /// </summary>
        /// <param name="data"></param>
        public override void UpdateHomePageData(EIInfo data)
        {
            // 数据发布
            IEventAggregator eventAggreator = Container.Resolve<IEventAggregator>();
            EIDataPublishedEvent dataPublishedEvent = eventAggreator.GetEvent<EIDataPublishedEvent>();
            dataPublishedEvent.Publish(data);
        }

        /// <summary>
        /// 选择主表显示从表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                this.InQu_fdForeignId.Value = e.AddedItems[0].GetType().GetProperty("fdKeyId").GetValue(e.AddedItems[0], null);
            }
            else
            {
                this.InQu_fdForeignId.Value = "0000";
            }

            if (e.AddedItems.Count > 0)
            {
                this.limitGrid.Refresh();
                return;
            }

            EIInfo eiInfo = this.BuildEIData(OperationMode.Query, eServiceName, "query", DataRange.All, null);
            eiInfo.GetBlock(EIConstants.QueryStatusBlock).GetRow(0).Add("fdDirId", "0000", true, false);
            if (eiInfo.Blocks.ContainsKey("limitresult"))
            {
                eiInfo.RemoveBlock("limitresult");
            }
            eiInfo.AddBlock("limitresult").Set("showCount", "true");
            eiInfo.GetBlock("limitresult").Set("count", "0");
            this.limitGrid.UpdateData(eiInfo);  
        }

    }
}
